# coding=utf-8
from django.contrib.auth import authenticate, login, logout
# from django.http import HttpResponseRedirect
from django.http.response import *
from django.template.context_processors import csrf

from WebApps.Auth.models import AccountModel, RoleModel
# from .render import render_ex, set_menu_selected
# from Apps.LN_game.views import set_menu_selected, render_ex
from Web.request import *
from .utils import *
from Web.menu import *
from ..forms import UserForm, PermissionForm, RoleForm
from WebApps.Auth.models import AccountModel as mAccount
from WebApps.Auth.models import PermissionModel as mPermission
from WebApps.Auth.models import RoleModel as mRole

menus += [
    menu(title="账户管理",
         url="/LN_game/account/page/query/",
         subs=[
             menu(
                 title="账户列表",
                 url='/LN_game/account/page/query/',
                 perms=['ProductModel.查询'],
             ),

             menu(
                 title="角色",
                 url='/LN_game/role/query/',
             ),
             menu(
                 title='权限',
                 url='/LN_game/permission/query/',
             )])
]


@register_url_handler(r'^LN_game/login/')
class LoginHandler(WebRequestHandler):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect("/LN_game/account/page/query/")
        request.user = None
        # html_data.update(csrf(request))
        return render(request, 'htmls/login.html', csrf(request))

    def post(self, request, *args, **kwargs):
        try:
            usern = request.POST['username']
            pwd = request.POST['password']
            # token = request.POST['csrfmiddlewaretoken']

            user = authenticate(username=usern, password=pwd)
            if user is None:
                return render(request, "htmls/login.html", {"error_message": "错误的用户名或密码",
                                                            "username": usern,
                                                            "password": pwd})

            login(request, user)
            return HttpResponseRedirect("/LN_game/account/page/query/")

        except Exception as e:
            return HttpResponse(ErrSystem(e.message))


@register_url_handler(r'^LN_game/logout/')
class LogoutHandler(WebRequestHandler):
    def get(self, request, *args, **kwargs):
        try:
            logout(request)
        except:
            pass

        return HttpResponseRedirect("/LN_game/login/")

    def post(self, request, *args, **kwargs):
        try:
            logout(request)
        except:
            pass

        return json_resp(ErrOk())


# 用户管理
@register_url_handler(r'LN_game/account/page/query/')
class QueryAccountHandler(WebRequestHandler):
    @login_required_ex(login_url="/LN_game/login/")
    @permission_required_ex("查询账户")
    def get(self, request, *args, **kwargs):
        try:
            id = request.GET.get('id')
            if id is not None:
                user = AccountModel.objects.get(pk=id)
                pass
            else:
                ctx = {
                    'query_account_url': '/LN_game/account/page/query/',
                    'add_account_url': '/LN_game/account/add/',
                    'edit_account_url': '/LN_game/account/edit/',
                    'delete_object_url': '/LN_game/account/delete/'
                }
                try:
                    rs = []
                    roles = RoleModel.objects.all()
                    for r in roles:
                        rs.append(r.role)
                    ctx.update({"roles": rs})
                except:
                    pass

                return html_render_ex(request, 'htmls/accounts.html', ctx, ["账户管理", "账户列表"])
        except Exception as e:
            return HttpResponseBadRequest()

    @login_required_ex(login_url="/LN_game/login/")
    @permission_required_ex("查询账户")
    def post(self, request, *args, **kwargs):
        accounts = mAccount.objects.all()
        resp_data = {
            'sEcho': request.POST.get('sEcho'),
            'iTotalRecords': len(accounts),
            'iTotalDisplayRecords': int(request.POST.get('iDisplayLength')),
            'aaData': []
        }

        for i in range(0, resp_data['iTotalRecords']):
            user_form = UserForm(instance=accounts[i],
                                 initial={"id": accounts[i].pk, "create_time": accounts[i].create_time})

            resp_data['aaData'].append({
                # "id": user_form['id'].value(),
                "username": user_form['username'].value(),
                "email": user_form['email'].value(),
                "role": user_form['role'].value(),
                "create_time": user_form['create_time'].value()
            })

        return JsonResponse(resp_data)
        pass


@register_url_handler(r'LN_game/account/add/')
class RegisterAccountHandler(WebRequestHandler):
    def err_handler(self, err, request):
        pass

    @login_required_ex(login_url="/LN_game/login/")
    def get(self, request, *args, **kwargs):
        return HttpResponseBadRequest()

    @login_required_ex(login_url="/LN_game/login/")
    @permission_required_ex("添加账户")
    def post(self, request, *args, **kwargs):
        try:
            acct_form = UserForm(request.POST)
            if not acct_form.is_valid():
                return json_resp(ErrInvalidForm(acct_form.errors))

            role = mRole.objects.get(role=acct_form['role'].value())
            user = mAccount.objects.create_user(acct_form['username'].value(),
                                         acct_form['email'].value(),
                                         acct_form['password'].value(),
                                         role)
            return json_resp(ErrOk())
        except Exception as e:
            print(e.message)
            return json_resp(ErrSystem(e.message))


@register_url_handler(r'LN_game/account/edit/')
class EditAccountHandler(WebRequestHandler):
    @login_required_ex(login_url="/LN_game/login/")
    def handler(self, request, data, files, *args, **kwargs):
        try:
            user = mAccount.objects.get(username=data['username'])
            uform = UserForm(data, instance=user)
            if not uform.is_valid():
                return json_resp(ErrInvalidForm(uform.errors))

            if not request.user.is_admin and user != request.user:
                return json_resp(ErrPermissionDenied())

            uform.save()
        except mAccount.DoesNotExist:
            return json_resp(ErrUserNotFound())
        except Exception as e:
            return json_resp(ErrInvalidForm())


@register_url_handler(r'^LN_game/account/delete/')
class DeleteAccountHandler(WebRequestHandler):
    def err_handler(self, err, request):
        pass

    @login_required_ex()
    @permission_required_ex("删除账户")
    def handler(self, request, data, files, *args, **kwargs):
        try:
            AccountModel.objects.get(pk=data['username']).delete()
            return json_resp(ErrOk())
        except AccountModel.DoesNotExist:
            return json_resp(ErrUserNotFound("用户不存在"))
        except Exception as e:
            return json_resp(ErrSystem(e.message))


# 角色管理
@register_url_handler(r'LN_game/role/query/')
class QueryRoleHandler(WebRequestHandler):
    @login_required_ex(login_url="/LN_game/login/")
    @permission_required_ex('查询角色')
    def get(self, request, *args, **kwargs):
        try:
            id = request.GET.get('role')
            if id is not None:
                user = AccountModel.objects.get(pk=id)
                pass
            else:
                perms = mPermission.objects.all()
                ctx = {
                    "query_role_url": "/LN_game/role/query/",
                    "edit_role_url": "/LN_game/role/edit/",
                    "delete_object_url": "/LN_game/role/delete/",
                    "add_role_url": "/LN_game/role/add/"
                }
                for p in mPermission.objects.all():
                    if not ctx.has_key('permissions'):
                        ctx['permissions'] = []

                    ctx['permissions'].append(p.code)

                return html_render_ex(request, 'htmls/roles.html', ctx, ("账户管理", "角色"))
        except Exception as e:
            return HttpResponseBadRequest()

    @login_required_ex(login_url='/LN_game/login/')
    @permission_required_ex("查询角色")
    def post(self, request, *args):
        try:
            roles = mRole.objects.all()
            resp_data = {
                'sEcho': request.POST.get('sEcho'),
                'iTotalRecords': len(roles),
                'iTotalDisplayRecords': int(request.POST.get('iDisplayLength')),
                'aaData': []
            }

            for i in range(0, resp_data['iTotalRecords']):
                role = RoleForm(instance=roles[i],
                                initial={"create_time": roles[i].create_time})

                resp_data['aaData'].append({
                    "role": role['role'].value(),
                    "description": role['description'].value(),
                    "create_time": role['create_time'].value(),
                    "is_superuser": True if roles[i].is_superuser else False,
                    "permissions": role['permissions'].value()
                })
            return JsonResponse(resp_data)
        except Exception as e:
            return json_resp(ErrSystem(e.message))

@register_url_handler(r'^LN_game/role/add/')
class AddRoleHandler(WebRequestHandler):
    @login_required_ex(login_url="/LN_game/login/")
    def handler(self, request, data, files, *args, **kwargs):
        try:
            role_form = RoleForm(data)
            if not role_form.is_valid():
                return json_resp(ErrInvalidForm(role_form.errors))

            role_form.save()
            return json_resp(ErrOk())
        except Exception as e:
            return json_resp(ErrSystem(e.message))

        pass

    pass

@register_url_handler(R'^LN_game/role/delete/')
class DeleteRoleHandler(WebRequestHandler):
    @login_required_ex(login_url='/LN_game/login/')
    def handler(self, request, data, files, *args, **kwargs):
        try:
            mRole.objects.get(pk=data['role']).delete()
        finally:
            return json_resp(ErrOk())


@register_url_handler(R'^LN_game/role/edit/')
class EditRoleHandler(WebRequestHandler):
    @login_required_ex(login_url='/LN_game/login/')
    def handler(self, request, data, files, *args, **kwargs):
        try:
            role_form = RoleForm(data, instance=mRole.objects.get(pk=data['role']))
            if not role_form.is_valid():
                return json_resp(ErrInvalidForm(role_form.errors))

            role_form.save()
            return json_resp(ErrOk())
        except Exception as e:
            return json_resp(ErrSystem())


# 权限管理
@register_url_handler(r'LN_game/permission/query/')
class QueryPermissionHandler(WebRequestHandler):
    @login_required_ex(login_url='/LN_game/login/')
    @permission_required_ex("查询权限")
    def get(self, request, *args, **kwargs):
        if request.GET.has_key("id"):
            id = request.GET['id']
            pass
        else:
            url_set = {
                "edit_permission_url": "/LN_game/permission/edit/",
                "query_permission_url": "/LN_game/permission/query/",
                "add_permission_url": "/LN_game/permission/add/",
                "delete_object_url": "/LN_game/permission/delete/",
            }
            return html_render_ex(request, "htmls/permissions.html", url_set, ("账户管理", "权限"))

    @login_required_ex(login_url='/LN_game/login/')
    @permission_required_ex("查询权限")
    def post(self, request, *args, **kwargs):
        try:
            perms = mPermission.objects.all()
            resp_data = {
                'sEcho': request.POST.get('sEcho'),
                'iTotalRecords': len(perms),
                'iTotalDisplayRecords': int(request.POST.get('iDisplayLength')),
                'aaData': []
            }

            for p in perms:
                try:
                    pform = PermissionForm(instance=p, initial={'create_time': p.create_time})
                    resp_data['aaData'].append(
                        {
                            "code": pform['code'].value(),
                            "name": pform['name'].value(),
                            "creator": pform['creator'].value(),
                            "create_time": pform['create_time'].value()
                        }
                    )
                except:
                    pass

            return JsonResponse(resp_data)
        except Exception as e:
            return JsonResponse({})


@register_url_handler(r'LN_game/permission/add/')
class AddPermissionHandler(WebRequestHandler):
    @login_required_ex(login_url='/LN_game/login/')
    @permission_required_ex("添加权限")
    def handler(self, request, data, files, *args, **kwargs):
        try:
            args = data.copy()
            # args.update(data);
            args.update({"creator": request.user.pk});
            perm = PermissionForm(args)
            if not perm.is_valid():
                return json_resp(ErrInvalidForm(perm.errors))
            perm.save(commit=True)
            return json_resp(ErrOk())
        except Exception as e:
            return json_resp(ErrSystem(e.message))


@register_url_handler(r'LN_game/permission/delete/')
class DeletePermissionHandler(WebRequestHandler):
    @login_required_ex(login_url='/LN_game/login/')
    @permission_required_ex("删除权限")
    def handler(self, request, data, files, *args, **kwargs):
        try:
            mPermission.objects.get(pk=data['code']).delete()
        finally:
            return json_resp(ErrOk())


@register_url_handler(r'LN_game/permission/edit/')
class EditPermissionHandler(WebRequestHandler):
    @login_required_ex(login_url='/LN_game/login/')
    @permission_required_ex('修改权限')
    def handler(self, request, data, files, *args, **kwargs):
        try:
            args = data.copy()
            args.update({"creator": request.user.pk})
            model = mPermission.objects.get(code=data['code'])
            perm = PermissionForm(args, instance=model)
            if not perm.is_valid():
                return json_resp(ErrInvalidForm(perm.errors['code']))

            perm.save()
            return json_resp(ErrOk())
        except mPermission.DoesNotExist:
            return json_resp(ErrPermissionNotFound("权限‘{0}’不存在".format(data['code'])))
        except Exception as e:
            return json_resp(ErrInvalidForm(e.message))
